package com.gzist.elderlyserviceplatform.scheduler;

import com.gzist.elderlyserviceplatform.entity.po.InfoNews;
import com.gzist.elderlyserviceplatform.mapper.InfoNewsMapper;
import com.gzist.elderlyserviceplatform.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 定时任务：同步 Redis 的浏览量数据到 MySQL
 */
@Service
@RequiredArgsConstructor
public class SyncDataService {

    private final InfoNewsMapper infoNewsMapper;
    private final RedisService redisService;
    private final StringRedisTemplate redisTemplate;

    @Scheduled(fixedRate = 3 * 60 * 1000) // 每 3 分钟同步一次
    public void syncViewCountToMySQL() {
        Set<String> keys = redisTemplate.keys("VIEW_COUNT_*");
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String newsId = key.replace("VIEW_COUNT_", "");
                Integer viewCount = redisService.getViewCount(newsId);
                if (viewCount != null) {
                    // 更新 MySQL 的浏览量：覆盖
                    infoNewsMapper.updateViewCount(newsId,viewCount);
                }
            }
        }
    }
}